import Konva from 'konva'
import { useEffect, useRef, useState } from 'react'
import { Image, Layer, Rect, Stage } from 'react-konva'
import useImage from 'use-image'

const URL = '/imgs/lion.png'

const FilterImage = () => {
  const [image] = useImage(URL, 'anonymous')
  const imageRef = useRef(null)

  // when image is loaded we need to cache the shape
  useEffect(() => {
    if (image) {
      // you many need to reapply cache on some props changes like shadow, stroke, etc.
      imageRef.current.cache()
    }
  }, [image])

  return <Image ref={imageRef} x={10} y={10} image={image} filters={[Konva.Filters.Blur]} blurRadius={10} />
}

const FilterRect = () => {
  const [color, setColor] = useState('green')
  const rectRef = useRef(null)

  const handleClick = () => {
    setColor(Konva.Util.getRandomColor())
  }

  useEffect(() => {
    rectRef.current.cache()
  }, [color])

  return (
    <Rect
      filters={[Konva.Filters.Noise]}
      noise={1}
      x={200}
      y={10}
      width={50}
      height={50}
      fill={color}
      shadowBlur={10}
      ref={rectRef}
      onClick={handleClick}
    />
  )
}

export default function View() {
  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <FilterImage />
        <FilterRect />
      </Layer>
    </Stage>
  )
}
